package com.jeesite.modules.stock.service;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class StockLogoParser {

    private final Map<String, String> logoMapper = new HashMap<>();

    @PostConstruct
    public void init() {
        try {
            InputStream resourceAsStream = this.getClass().getClassLoader()
                    .getResourceAsStream("stock_logo_mapping.json");
            if (resourceAsStream != null) {
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                byte[] b = new byte[4098];
                int len;
                while ((len = resourceAsStream.read(b)) > -1) {
                    bout.write(b, 0, len);
                }
                String content = bout.toString(StandardCharsets.UTF_8);
                bout.close();
                resourceAsStream.close();
                JSONObject jo = JSON.parseObject(content);
                Set<String> names = jo.keySet();
                for (String name : names) {
                    String value = jo.getString(name);
                    logoMapper.put(name, value);
                }
            }
        } catch (Exception e) {
            log.error("初始化logo数据失败,errMsg:{}", e.getMessage(), e);
        }
    }

    /**
     * 得到股票logo文件名称
     *
     * @param stockCode 股票代码
     * @return logo文件名称，存放地址resources/logos/*
     */
    public String getStockLogoFileName(String stockCode) {
        return logoMapper.get(stockCode);
    }
}
